<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col
          ><el-button type="primary" @click="addRoleDialogVisible = true"
            >添加角色</el-button
          ></el-col
        >
      </el-row>
      <el-table :data="rolesList" row-key="id">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editRolesById(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="success"
              size="mini"
              icon="el-icon-delete"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-share"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="closeAddRolesDialog"
    >
      <el-form
        :model="addRolesInfo"
        :rules="addRolesRules"
        ref="addRolesFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleDialogVisible"
      width="50%"
      @close="closeEditRolesDialog"
    >
      <el-form
        :model="editRole"
        :rules="editRolesRules"
        ref="editRolesFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog
      title="提示"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightClose"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="treeKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "myRoles",
  data() {
    return {
      addRoleDialogVisible: false,
      editRoleDialogVisible: false,
      setRightDialogVisible: false,
      //角色列表
      rolesList: [],
      //权限列表
      rightList: [],
      addRolesInfo: {
        roleName: "",
        roleDesc: "",
      },
      addRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      editRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
      },
      //根据id查询到角色
      editRole: {},
      //树形控件的属性绑定对象
      treeProps: {
        label: "authName",
        children: "children",
      },
      //默认选中结点的数组
      treeKeys: [],
      roleId: "", //当前即将分配权限的角色id
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取所有角色
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败！");
      this.rolesList = res.data;
      // console.log(res);
    },
    //添加角色
    async addRole() {
      const { data: res } = await this.$http.post("roles", this.addRolesInfo);
      console.log(res);
      if (res.meta.status !== 201) return this.$message.error("添加角色失败！");
      this.getRolesList();
      this.addRoleDialogVisible = false;
      this.$message.success("添加角色成功！");
    },
    //关闭添加角色的对话框重置表单
    closeAddRolesDialog() {
      this.$refs.addRolesFormRef.resetFields();
    },
    //通过id删除角色
    async removeRoleById(id) {
      // console.log(id);
      const result = await this.$confirm(
        "此操作将永久删除该角色, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result === "confirm") {
        const { data: res } = await this.$http.delete("roles/" + id);
        if (res.meta.status !== 200) return this.$message.error("删除失败！");
        this.$message.success("删除角色成功！");
        this.getRolesList();
      }
    },
    //根据id查询角色
    async editRolesById(id) {
      this.editRoleDialogVisible = true;
      const { data: res } = await this.$http.get("roles/" + id);
      // console.log(res);
      this.editRole = res.data;
    },
    async editRoles() {
      // console.log(this.editRole.roleId);
      const { data: res } = await this.$http.put(
        "roles/" + this.editRole.roleId,
        {
          roleName: this.editRole.roleName,
          roleDesc: this.editRole.roleDesc,
        }
      );
      if (res.meta.status !== 200) return this.$message.error("更新失败！");
      this.$message.success("更新成功！");
      this.getRolesList();
      this.editRoleDialogVisible = false;
    },
    //关闭编辑角色的对话框重置表单
    closeEditRolesDialog() {
      this.$refs.editRolesFormRef.resetFields();
    },
    //删除权限
    async removeRightById(role, rightId) {
      const result = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (result !== "confirm") {
        return this.$message.info("取消了删除！");
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除失败！");
      this.$message.success("删除成功！");
      role.children = res.data;
    },
    //显示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id;
      console.log(role);
      const { data: res } = await this.$http.get("rights/tree");
      // console.log(res);
      this.rightList = res.data;
      this.getLeafKeys(role, this.treeKeys);
      this.setRightDialogVisible = true;
    },
    //获取三级结点的id
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        return this.getLeafKeys(item, arr);
      });
    },
    //监听分配权限的关闭事件
    setRightClose() {
      this.treeKeys = [];
    },
    //点击对话框的确定为角色分配权限
    async allotRight() {
      const key = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];

      const strId = key.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: strId }
      );
      if (res.meta.status !== 200) return this.$message.error("更新失败！");
      this.$message.success("更新成功！");
      this.getRolesList();
      this.setRightDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}
.el-tag {
  margin: 5px;
}
.bdbottom {
  border-top: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>